import uix
import util
import blue
import fontflags
import uicls
import uiconst
import uiutil
import trinity
import listentry
import _weakref

class Edit(uicls.EditCore):
    __guid__ = 'uicls.Edit'
    default_align = uiconst.TOALL
    default_pos = (0, 0, 0, 0)
    default_fontcolor = (1.0, 1.0, 1.0, 0.75)

    def OnDropDataDelegate(self, node, nodes):
        uicls.EditCore.OnDropDataDelegate(self, node, nodes)
        if self.readonly:
            return 
        for entry in nodes:
            if (entry.__guid__ in ('listentry.User', 'listentry.ChatUser', 'listentry.Sender')):
                link = ((('showinfo:' + str(entry.info.typeID)) + '//') + str(entry.charID))
                self.AddLink(entry.info.name, link)
            elif ((entry.__guid__ == 'listentry.PlaceEntry') and self.allowPrivateDrops):
                bookmarkID = entry.bm.bookmarkID
                bms = sm.GetService('addressbook').GetBookmarks()
                if (bookmarkID in bms):
                    bookmark = bms[bookmarkID]
                    (hint, comment,) = sm.GetService('addressbook').UnzipMemo(bookmark.memo)
                link = ((('showinfo:' + str(bms[bookmarkID].typeID)) + '//') + str(bms[bookmarkID].itemID))
                self.AddLink(hint, link)
            elif ((entry.__guid__ == 'listentry.NoteItem') and self.allowPrivateDrops):
                link = ('note:' + str(entry.noteID))
                self.AddLink(entry.label, link)
            elif (entry.__guid__ in ('listentry.InvItem', 'xtriui.InvItem', 'xtriui.ShipUIModule', 'listentry.InvAssetItem')):
                if (type(entry.rec.itemID) is tuple):
                    link = ('showinfo:' + str(entry.rec.typeID))
                else:
                    link = ((('showinfo:' + str(entry.rec.typeID)) + '//') + str(entry.rec.itemID))
                self.AddLink(entry.name, link)
            elif (entry.__guid__ in ('listentry.VirtualAgentMissionEntry',)):
                link = ((('fleetmission:' + str(entry.agentID)) + '//') + str(entry.charID))
                self.AddLink(entry.label, link)
            elif (entry.__guid__ in ('xtriui.CertSlot',)):
                if entry.rec.certID:
                    link = ('CertSlot:%s' % entry.rec.certID)
                    self.AddLink(entry.rec.label, link)
                else:
                    link = ('showinfo:%s' % entry.rec.typeID)
                    self.AddLink(entry.rec.label, link)
            elif entry.__guid__.startswith('listentry.ContractEntry'):
                link = ((('contract:' + str(entry.solarSystemID)) + '//') + str(entry.contractID))
                self.AddLink(entry.name.replace('&gt;', '>'), link)
            elif (entry.__guid__ in ('listentry.FleetFinderEntry',)):
                link = ('fleet:%s' % entry.fleet.fleetID)
                self.AddLink((entry.fleet.fleetName or mls.UI_GENERIC_UNKNOWN), link)
            elif (entry.__guid__ == 'xtriui.ListSurroundingsBtn'):
                if ((not entry.typeID) and (not entry.itemID)):
                    return 
                link = ((('showinfo:' + str(entry.typeID)) + '//') + str(entry.itemID))
                self.AddLink(entry.label, link)
            elif (entry.__guid__ == 'listentry.FittingEntry'):
                PADDING = 12
                link = ('fitting:' + sm.StartService('fittingSvc').GetStringForFitting(entry.fitting))
                roomLeft = (self.RoomLeft() - PADDING)
                if (len(link) >= roomLeft):
                    if (roomLeft < 14):
                        raise UserError('LinkTooLong')
                    if (eve.Message('ConfirmTruncateLink', {'numchar': len(link),
                     'maxchar': roomLeft}, uiconst.YESNO, suppress=uiconst.ID_YES) != uiconst.ID_YES):
                        return 
                    link = link[:roomLeft]
                self.AddLink(entry.fitting.name, link)
            else:
                if (entry.__guid__ == 'listentry.GenericMarketItem'):
                    link = ('showinfo:' + str(entry.typeID))
                    self.AddLink(entry.label, link)




    def ApplyGameSelection(self, what, data, changeObjs):
        if ((what == 6) and len(changeObjs)):
            key = {}
            if data:
                key['link'] = data['link']
                t = self.DoSearch(key['link'], data['text'])
                if not t:
                    return 
                else:
                    format = [{'type': 'checkbox',
                      'label': '_hide',
                      'text': 'http://',
                      'key': 'http://',
                      'required': 1,
                      'setvalue': 1,
                      'frame': 1,
                      'group': 'link',
                      'onchange': self.OnLinkTypeChange},
                     {'type': 'btline'},
                     {'type': 'checkbox',
                      'label': '_hide',
                      'text': mls.UI_GENERIC_CHARACTER,
                      'key': 'char',
                      'required': 1,
                      'setvalue': 0,
                      'frame': 1,
                      'group': 'link',
                      'onchange': self.OnLinkTypeChange},
                     {'type': 'checkbox',
                      'label': '_hide',
                      'text': mls.UI_GENERIC_CORPORATION,
                      'key': 'corp',
                      'required': 1,
                      'setvalue': 0,
                      'frame': 1,
                      'group': 'link',
                      'onchange': self.OnLinkTypeChange},
                     {'type': 'btline'},
                     {'type': 'checkbox',
                      'label': '_hide',
                      'text': mls.UI_GENERIC_ITEMTYPE,
                      'key': 'type',
                      'required': 1,
                      'setvalue': 0,
                      'frame': 1,
                      'group': 'link',
                      'onchange': self.OnLinkTypeChange},
                     {'type': 'btline'},
                     {'type': 'checkbox',
                      'label': '_hide',
                      'text': mls.UI_GENERIC_SOLARSYSTEM,
                      'key': 'solarsystem',
                      'required': 1,
                      'setvalue': 0,
                      'frame': 1,
                      'group': 'link',
                      'onchange': self.OnLinkTypeChange},
                     {'type': 'checkbox',
                      'label': '_hide',
                      'text': mls.UI_GENERIC_STATION,
                      'key': 'station',
                      'required': 1,
                      'setvalue': 0,
                      'frame': 1,
                      'group': 'link',
                      'onchange': self.OnLinkTypeChange},
                     {'type': 'btline'},
                     {'type': 'edit',
                      'label': mls.GENERIC_LINK,
                      'text': 'http://',
                      'labelwidth': 100,
                      'required': 1,
                      'key': 'txt',
                      'frame': 1}]
                    key = self.AskLink(mls.UI_GENERIC_ENTERLINK, format, width=400)
                anchor = -1
                if key:
                    link = key['link']
                    if (link == None):
                        return 
                    if (link in ('char', 'corp', 'solarsystem', 'station', 'type')):
                        if not self.typeID:
                            t = self.DoSearch(link, key['txt'])
                            if not t:
                                return 
                        anchor = ('showinfo:' + str(self.typeID))
                        if self.itemID:
                            anchor += ('//' + str(self.itemID))
                    else:
                        if (link == 'fleet'):
                            anchor = ('fleet:' + str(self.itemID))
                    anchor = (key['link'] + key['txt'])
                return anchor
            return -1



    def OnLinkTypeChange(self, chkbox, *args):
        if chkbox.GetValue():
            self.itemID = self.typeID = 0
            self.key = chkbox.data['key']
            text = uiutil.GetChild(chkbox, 'text')
            wnd = chkbox.FindParentByName(mls.UI_SHARED_GENERATELINK)
            if not wnd:
                return 
            editParent = uiutil.FindChild(wnd, 'editField')
            if (editParent is not None):
                label = uiutil.FindChild(editParent, 'label')
                label.text = text.text
                edit = uiutil.FindChild(editParent, 'edit_txt')
                edit.SetValue('')
                self.sr.searchbutt = uiutil.FindChild(editParent, 'button')
                if (self.key in ('char', 'corp', 'type', 'solarsystem', 'station')):
                    if (self.sr.searchbutt == None):
                        self.sr.searchbutt = uicls.Button(parent=editParent, label=mls.UI_CMD_SEARCH, pos=(0, 0, 0, 0), func=self.OnSearch, btn_default=0, align=uiconst.TOPRIGHT)
                    else:
                        self.sr.searchbutt.state = uiconst.UI_NORMAL
                    edit.width = 55
                else:
                    if (self.sr.searchbutt != None):
                        self.sr.searchbutt.state = uiconst.UI_HIDDEN
                        edit.width = 0



    def OnSearch(self, *args):
        wnd = self.sr.searchbutt.FindParentByName(mls.UI_SHARED_GENERATELINK)
        if not wnd:
            return 
        editParent = uiutil.FindChild(wnd, 'editField')
        edit = uiutil.FindChild(editParent, 'edit_txt')
        val = edit.GetValue().strip().lower()
        name = self.DoSearch(self.key, val)
        if (name is not None):
            edit.SetValue(name)



    def DoSearch(self, key, val):
        self.itemID = None
        self.typeID = None
        id = None
        name = ''
        if (key == 'type'):
            if (getattr(self, 'markettypes', None) == None):
                from contractutils import GetMarketTypes
                self.markettypes = GetMarketTypes()
            itemTypes = []
            for t in self.markettypes:
                if (t.typeName.lower().find(val.lower()) >= 0):
                    itemTypes.append((cfg.invtypes.Get(t.typeID).name,
                     None,
                     t.typeID))

            if not itemTypes:
                eve.Message('NoItemTypesFound')
                return 
            id = uix.ListWnd(itemTypes, 'item', mls.UI_GENERIC_SELECTITEMTYPE, None, 1)
        else:
            group = None
            cat = None
            filterGroups = []
            hideNPC = 0
            if (key == 'solarsystem'):
                group = const.groupSolarSystem
            elif (key == 'station'):
                group = const.groupStation
            elif (key == 'char'):
                cat = const.categoryOwner
                filterGroups = [const.groupCharacter]
            elif (key == 'corp'):
                cat = const.categoryOwner
                filterGroups = [const.groupCorporation]
            id = uix.Search(val, group, cat, hideNPC=hideNPC, filterGroups=filterGroups)
        name = ''
        if id:
            self.itemID = id
            self.typeID = 0
            if (key in ('char', 'corp')):
                o = cfg.eveowners.Get(id)
                self.typeID = o.typeID
                name = o.name
            elif (key == 'solarsystem'):
                self.typeID = const.typeSolarSystem
                l = cfg.evelocations.Get(id)
                name = l.name
            elif (key == 'station'):
                self.typeID = sm.GetService('ui').GetStation(id).stationTypeID
                l = cfg.evelocations.Get(id)
                name = l.name
            else:
                if (key == 'type'):
                    self.typeID = id[2]
                    self.itemID = None
                    name = id[0]
        return name



    def AskLink(self, label = '', lines = [], width = 280):
        icon = uix.QUESTION
        format = (([{'type': 'btline'}, {'type': 'text',
          'text': label,
          'frame': 1}] + lines) + [{'type': 'bbline'}])
        btns = uiconst.OKCANCEL
        retval = uix.HybridWnd(format, mls.UI_SHARED_GENERATELINK, 1, None, uiconst.OKCANCEL, minW=width, minH=110, icon=icon)
        if retval:
            return retval



    def AddLink(self, text, link = None):
        self.SetSelectionRange(None, None)
        shiftCursor = len(text)
        (node, obj, npos,) = self.GetNodeAndTextObjectFromGlobalCursor()
        if obj.letters:
            orgString = obj.letters
            orgIndex = node.stack.index(obj)
            obj.letters = orgString[:npos]
            firstSpaceObj = self.GetTextObject(' ')
            firstSpaceObj.a = None
            node.stack.insert((orgIndex + 1), firstSpaceObj)
            newObject = self.GetTextObject(' ')
            newObject.a = None
            node.stack.insert((orgIndex + 2), newObject)
            restObj = obj.Copy()
            restObj.letters = orgString[npos:]
            if restObj.letters:
                node.stack.insert((orgIndex + 3), restObj)
        else:
            newObject = obj
            newObject.a = None
        newObject.letters = text
        if (link is not None):
            anchor = link
            attr = util.KeyVal()
            attr.href = anchor
            attr.alt = anchor
            newObject.a = attr
        endSpaceObj = newObject.Copy()
        endSpaceObj.letters = ' '
        endSpaceObj.a = None
        node.stack.insert((node.stack.index(newObject) + 1), endSpaceObj)
        self._OnResize(0)
        self.SetCursorPosAtObjectEnd(newObject)
        uicore.registry.SetFocus(self)




class FontAttribPanel(uicls.FontAttribPanelCore):
    __guid__ = 'uicls.FontAttribPanel'

    def Expand(self):
        uicore.layer.main.state = uix.UI_DISABLED
        self.expanding = 1
        if sm.GetService('connection').IsConnected():
            eve.Message('ComboExpand')
        uix.LogInfo('Combo', self.name, 'expanding')
        colorpar = uicls.Container(name='colors', align=uiconst.TOPLEFT, width=130, height=133)
        uicore.layer.menu.children.insert(0, colorpar)
        colorscroll = uicls.Scroll(parent=colorpar)
        colors = [((1.0, 1.0, 1.0, 1.0), 'white'),
         ((0.7, 0.7, 0.7, 1.0), 'grey 70%'),
         ((0.3, 0.3, 0.3, 1.0), 'grey 30%'),
         ((0.0, 0.0, 0.0, 1.0), 'black'),
         ((1.0, 1.0, 0.0, 1.0), 'yellow'),
         ((0.0, 1.0, 0.0, 1.0), 'green'),
         ((1.0, 0.0, 0.0, 1.0), 'red'),
         ((0.0, 0.0, 1.0, 1.0), 'blue'),
         ((0.5, 0.5, 0.0, 1.0), 'dark yellow'),
         ((0.0, 0.5, 0.0, 1.0), 'dark green'),
         ((0.5, 0.0, 0.0, 1.0), 'dark red'),
         ((0.0, 0.0, 0.5, 1.0), 'dark blue'),
         ((0.5, 0.0, 0.5, 1.0), 'dark mangenta'),
         ((0.0, 1.0, 1.0, 1.0), 'cyan'),
         ((1.0, 0.0, 1.0, 1.0), 'mangenta'),
         ((0.0, 0.5, 1.0, 1.0), 'dark blue'),
         ((1.0, 0.5, 0.0, 1.0), 'dark blue')]
        x = y = 0
        scrolllist = []
        icons = []
        for each in colors:
            (color, labelstr,) = each
            col = trinity.TriColor(*color)
            icons.append(('res:/UI/Icon/Mapped/icon09_14.blue',
             col,
             color,
             self.PickCol))
            x += 1
            if (x == 4):
                scrolllist.append(listentry.Get('Icons', {'icons': icons}))
                icons = []
                y += 1
                x = 0

        colorscroll.Load(32, scrolllist)
        uiutil.Update(colorpar)
        (colorpar.left, colorpar.top,) = (self.sr.color.absoluteLeft, [(self.sr.color.absoluteTop + self.sr.color.height), (self.sr.color.absoluteTop - colorpar.height)][(((self.sr.color.absoluteTop + self.sr.color.height) + colorpar.height) > eve.triapp.height)])
        colorpar.state = uix.UI_NORMAL
        self.sr.colorscroll = _weakref.ref(colorscroll)
        uicore.event.RegisterForTriuiEvents(uix.UI_MOUSEUP, self.OnGlobalClick)
        self.expanding = 0
        self.expanded = 1
        uix.LogInfo('Colors', self.name, 'expanded')




